package com.ai.imagetext.service;

import com.ai.imagetext.dto.OperationLogDTO;
import com.ai.imagetext.entity.GeneratedImage;
import com.ai.imagetext.entity.OperationLog;
import com.ai.imagetext.entity.TextContent;
import com.ai.imagetext.repository.GeneratedImageRepository;
import com.ai.imagetext.repository.OperationLogRepository;
import com.ai.imagetext.repository.TextContentRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class OperationLogService {

    private final OperationLogRepository operationLogRepository;

    private final TextContentRepository textContentRepository;

    private final GeneratedImageRepository generatedImageRepository;

    /**
     * 记录操作日志
     */
    @Transactional
    public OperationLogDTO recordOperation(Long userId, Integer type, Long imageId, Long generalId) {
        try {
            OperationLog operationLog = new OperationLog();
            operationLog.setUserId(userId);
            operationLog.setType(type);
            operationLog.setImageId(imageId);
            operationLog.setGeneralId(generalId);
            operationLog.setIsDelete(false);

            OperationLog saved = operationLogRepository.save(operationLog);
            log.info("操作日志记录成功: userId={}, type={}, imageId={}, generalId={}",
                    userId, type, imageId, generalId);

            return OperationLogDTO.fromEntity(saved);
        } catch (Exception e) {
            log.error("记录操作日志失败: userId={}, type={}, imageId={}, generalId={}",
                    userId, type, imageId, generalId, e);
            throw new RuntimeException("记录操作日志失败", e);
        }
    }

    /**
     * 根据用户ID和操作类型查询操作日志
     */
    public List<OperationLogDTO> findByUserIdAndType(Long userId, Integer type) {
        System.out.println("userId = " + userId + ", type = " + type);
        System.out.println("-----");
        List<OperationLog> logs = operationLogRepository.findTop10ByUserIdAndTypeAndIsDeleteFalseOrderByCreateTimeDesc(userId, type);
        for (OperationLog operationLog : logs) {
            System.out.println("开始输出日志信息");
            System.out.println(operationLog.getId() + " " + operationLog.getType() + " " + operationLog.getCreateTime());
        }
        return logs.stream()
                .map(OperationLogDTO::fromEntity)
                .collect(Collectors.toList());
    }

    /**
     * 根据日志信息查询图生文案的实体
     */
    public TextContent findContentByGeneralId(Long generalId) {
        return textContentRepository.findByIdAndIsDeletedFalse(generalId).orElse(null);
    }

    /**
     * 根据日志信息查询图生图的实体
     */
    public GeneratedImage findPictureByGeneralId(Long generalId) {
        return generatedImageRepository.findByIdAndIsDeletedFalse(generalId).orElse(null);
    }

    /**
     * 分页查询操作日志
     */
    public Page<OperationLogDTO> findAll(Pageable pageable) {
        Page<OperationLog> logs = operationLogRepository.findAll(pageable);
        return logs.map(OperationLogDTO::fromEntity);
    }

    /**
     * 软删除操作日志
     */
    @Transactional
    public void softDelete(Integer logId) {
        operationLogRepository.findById(logId).ifPresent(log -> {
            log.setIsDelete(true);
            operationLogRepository.save(log);
            System.out.println("操作日志软删除成功: logId=" + logId);
        });
    }

    /**
     * 记录图生文操作
     */
    @Transactional
    public OperationLogDTO recordImageToTextOperation(Long userId, Long imageId, Long textContentId) {
        return recordOperation(userId, 0, imageId, textContentId);
    }

    /**
     * 记录图生图操作
     */
    @Transactional
    public OperationLogDTO recordImageToImageOperation(Long userId, Long imageId, Long generatedImageId) {
        return recordOperation(userId, 1, imageId, generatedImageId);
    }

}
